<?php

/**
 * Beaver_Controller_Action
 *
 * @category   Beaver
 * @package    Beaver
 * @subpackage Beaver_Controller
 * @uses       Zend_Controller_Action
 * @author     Mihály Kuprivecz
 */

class Beaver_Controller_Action extends Zend_Controller_Action
{

    /**
     * Zend_Controller_Request_Abstract object wrapping the request environment
     * @var Zend_Controller_Request_Abstract
     */
    protected $_request = null;

    /**
     * Zend_Controller_Response_Abstract object wrapping the response
     * @var Zend_Controller_Response_Abstract
     */
    protected $_response = null;
    
    /**
     * Container of Ext.Direct request
     * @var Array
     */
    protected $_extData = null;
    
    /**
     * State of Ext direct json render
     * @var Boolean
     */
    protected $_extResponseRender = false; 
    
    /**
     * Zend_Layout object wrapping
     * @var Zend_Layout
     */
    protected $_layout = null;
    
    /**
     * If CRUD model is setted, the CRUD methods are automatically run
     * @var Beaver_Model
     */
    protected $_crudModel = null;

    /**
     * Class constructor
     *
     * @param Zend_Controller_Request_Abstract $request
     * @param Zend_Controller_Response_Abstract $response
     * @param array $invokeArgs Any additional invocation arguments
     * @return void
     */
    public function __construct(Zend_Controller_Request_Abstract $request, Zend_Controller_Response_Abstract $response, array $invokeArgs = array())
    {
    	parent::__construct( $request, $response, $invokeArgs );
    	
    	//date_default_timezone_set('Europe/Budapest');
    	
    	//load the controller specific configuration file
    	if(!defined("CONFIG_PATH")) define("CONFIG_PATH", APPLICATION_PATH . DIRECTORY_SEPARATOR . "configs");
		
    	// Set the language
    	Beaver_Language::getInstance()
    	->registerLanguagePath(CONFIG_PATH . DIRECTORY_SEPARATOR . "languages")
    	->registerLanguageFile("Validator")
    	->registerLanguageFile(ucfirst($request->getControllerName()));
    	
		// Set the lifetime of the session
		//$session = $this->getInvokeArg("bootstrap")->getOption("session");
		//Zend_Session::rememberMe($session["lifetime"]);
		
		
		//set the layout reference
		$this->_layout = Zend_Layout::getMvcInstance();
		
		$this->setResponseToJavascript();
		
		if( isset( $this->_request->extData ) )
		{
			/**
			 * Error messages container
			 */
			$this->view->errors = array();
			$this->_extResponseRender = true;
			$this->setResponseToJson();
		}
		
		$this->view->setBasePath(BEAVER_APPLICATION_PATH . "/views/");
		$this->view->addBasePath(APPLICATION_PATH . "/views/");
    }
    
    public function postDispatch()
	{
		$this->view->beaverLanguage = Beaver_Language::getInstance();
		if ( $this->_extResponseRender )
		{
			$this->setResponseToJson();
			
			$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
			$viewVars = $this->view->getVars();
			
			if($this->getFrontController()->getPlugin("Zend_Controller_Plugin_ActionStack"))
			{
				$extData = $this->getFrontController()->getPlugin("Zend_Controller_Plugin_ActionStack")->getRequest()->getParam("extData");
			}
			else
			{
				$extData = $this->_request->getParam("extData");
			}
			
			if ( !isset($extData["type"]) && !isset($viewVars["type"]) )
			{
				throw new Beaver_Exception("Type required to render ext response");
			}
			if ( !isset($viewVars["type"]) )    $this->view->type    = $extData["type"];
			
			switch ($this->view->type)
			{
				case "rpc":
					// Exception if not set the tid and the request isn't contain it 
					if ( !isset($viewVars["tid"]) && !isset($extData["tid"]) )
					{
						throw new Beaver_Exception("'Tid' is required to set in rpc response)");
					}
					// If not set the tid get it from extData
					if ( !isset($viewVars["tid"]) ) $this->view->tid     = $extData["tid"];
					
					
					// Exception if not set the action and the request isn't contain it
					if ( !isset($viewVars["action"]) && !isset($extData["action"]) )
					{
						throw new Beaver_Exception("'action' is required to set in rpc response)");
					}
					// If not set the action get it from extData
					if ( !isset($viewVars["action"]) ) $this->view->action     = $extData["action"];
					
					
					// Exception if not set the method and the request isn't contain it
					if ( !isset($viewVars["method"]) && !isset($extData["method"]) )
					{
						throw new Beaver_Exception("'method' is required to set in rpc response)");
					}
					// If not set the method get it from extData
					if ( !isset($viewVars["method"]) ) $this->view->method     = $extData["method"];
					
					
					if ( isset($viewVars["result"]) )
					{
						$this->view->result = Zend_Json_Encoder::encode($viewVars["result"]);
					}
					
					// If not set the success state
					if ( !isset($viewVars["success"]) ) $this->view->success = true;
					
					// Convert to string
					if ( $this->view->success === true ) $this->view->success  = "true";
					if ( $this->view->success === false ) $this->view->success = "false";
					
					if ( isset($viewVars["errors"]) && is_array($viewVars["errors"]) && count($viewVars["errors"]) > 0 )
					{
						$this->view->errors = json_encode($viewVars["errors"]);
						$this->view->success = false;
					}
					else
					{
						unset($this->view->errors);
						//$this->view->errors = json_encode(array());
					}
					
					$this->view->isForm = false;
					
					if( isset($extData["isForm"]) && $extData["isForm"] )
					{
						$this->view->isForm = true;
						$this->view->debug_formPacket = Zend_Json_Encoder::encode($extData);
						//json_encode($extData);
					}
					
					if ( isset($viewVars["data"]) && ( is_array($viewVars["data"]) || is_object($viewVars["data"]) ) )
					{
						$this->view->data = Zend_Json_Encoder::encode($viewVars["data"]);
						//json_encode($viewVars["data"]);
					}
					break;
				case "exception":
					// it set by Error handler
					break;
				case "event":
					if ( !isset($viewVars["name"]) && !isset($extData["name"]) )
					{
						throw new Beaver_Exception("'name' is required to set in event response)");
					}
					if ( isset($viewVars["data"]) )
					{
						$this->view->data = json_encode($viewVars["data"]);
					}
					else
					{
						$this->view->data = json_encode(array());
					}
					
					break;
				default:
					throw new Beaver_Exception("Invalid Ext response type ('" . $this->view->type . "')");
					break;
			}
			
			
			//Init a log entry
					
			
			$viewRenderer->renderScript("extdirect.js");
			if($this->getFrontController()->getPlugin("Zend_Controller_Plugin_ActionStack"))
			{
				echo $this->getFrontController()->getPlugin("Zend_Controller_Plugin_ActionStack")->getRequest()->getParam("viewExtra");
				$viewVars = $this->view->getVars();
				//var_dump($viewVars);
				$log = new Beaver_Model_Log();
				$log->controller = $viewVars["action"];
				$log->action     = $viewVars["method"];
				$log->is_form    = (int) $viewVars["isForm"];
				$log->params     = Zend_Json_Encoder::encode($this->getFrontController()->getPlugin("Zend_Controller_Plugin_ActionStack")->getRequest()->getParam("extParams"));
				$log->success    = 0;
				if ($viewVars["success"] == "true")
				{
					$log->success    = 1;
				}
				$auth = Zend_Auth::getInstance();
				$user = $auth->getIdentity();
				if( isset($user["id"]))
				{
					$log->user = (int) $user["id"];
				}
				$log->save();
			}
			
			$this->view->clearVars();
		}
	}
	
	public function setResponseToJson()
	{
		$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
		$viewRenderer->setViewSuffix("json");
		$this->_layout->setViewSuffix("json")->setLayout('empty');
		//$this->getResponse()->setHeader('Content-Type', 'application/json');
	}
	
	public function setResponseToHtml()
	{
		$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
		$viewRenderer->setViewSuffix("html");
		$this->_layout->setViewSuffix("html")->setLayout('empty');
		$this->getResponse()->setHeader('Content-Type', 'text/html');
	}
	
	public function setResponseToJavascript()
	{
		$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
		$viewRenderer->setViewSuffix("js");
		$this->_layout->setViewSuffix("js")->setLayout('empty');
		$this->getResponse()->setHeader('Content-Type', 'text/javascript');
	}
	
	/**
	 * Render the Module js layout
	 *
	 */
	public function indexAction() {	}
	
	
	/**
	 * CRUD createAction
	 */
	public function createAction()
	{
		if ( null != $this->_crudModel  )
		{
			$this->_crudModel->setAttributes($this->_request->extParams[0]["data"]);
			
			$data = $this->_request->extParams[0]["data"];
			$result = $this->_crudModel->save();
			if ( false == $result || is_object($result) || is_array($result) )
			{
				$message = "Error!";
				
				if ( is_object($result) )
				{
					foreach ($result as $name => $validation )
					{
						foreach ($validation["errorMessages"] as $error ) {
							$message .= $name . ": " . $error . "<br/>";
						}
					}
				}
				$this->view->message = $message;
				$this->view->success = false;
			}
			else
			{
				$data = $this->_crudModel->getAttributes();
				$data["id"] = $result;
				$this->view->data    = $data;
			}			
		}
	}
	
	/**
	 * CRUD readAction
	 */
	public function readAction()
	{
		if ( null != $this->_crudModel  )
		{
			$count  = null;
			$offset = null;
			$order  = null;
			
			if ( isset($this->_request->extParams[0]["limit"]) )
			{
				$count = $this->_request->extParams[0]["limit"];
			}
			if( isset($this->_request->extParams[0]["start"] ) )
			{
				$offset = $this->_request->extParams[0]["start"];
			}
			if( isset($this->_request->extParams[0]["sort"] ) )
			{
				$order = $this->_request->extParams[0]["sort"];
				if( isset($this->_request->extParams[0]["dir"] ) )
				{
					$order = $order . " " . $this->_request->extParams[0]["dir"];
				}
			}
			// prepare the filter from the params keys
			$filter = array();
			foreach ($this->_request->extParams[0] as $key => $param)
			{
				if(substr($key,0,8) == "filter[]")
				{
					$actualParam = explode("[",substr($key,8));
					$filter[] = array(
						"attribute"  => substr($actualParam[1],0,-1),
						"type"       => substr($actualParam[2],0,-1),
						"comparsion" => substr($actualParam[3],0,-1),
						"value"      => $param
					);
				}
			}
			
			$countries = $this->_crudModel->findAll($filter,$order,$count,$offset);
			$this->view->data  = $countries;
			$this->view->total = $this->_crudModel->findCount($filter);
		}
	}
	
	/**
	 * CRUD updateAction
	 */
	public function updateAction()
	{
		if ( null != $this->_crudModel  )
		{
			$this->_crudModel->setAttributes($this->_request->extParams[0]["data"]);
			$result  = $this->_crudModel->save();
			//$this->view->message = '( ' . $this->_crudModel->id . ' ) módosítás sikeres!';
	
			if ( !is_integer($result) ){
				$message = "";
				foreach ($result as $name => $validation )
				{
					foreach ($validation["errorMessages"] as $error ) {
						$message .= $name . ": " . $error . "<br/>";
					}
				}
				$this->view->message = $message;
				$this->view->success = false;
			}
			elseif ( $result == 0 )
			{
				$this->view->message = "Nem történt módosítás!";
				$this->view->success = false;
			}
			$this->_crudModel->find();
			$this->view->data = $this->_crudModel->getAttributes();
		}
	}
	
	/**
	 * CRUD destroyAction
	 */
	public function destroyAction()
	{
		if ( null != $this->_crudModel  )
		{
			$this->_crudModel->id = $this->_request->extParams[0]["data"];
			$result = $this->_crudModel->delete();
			if ( $result == 0 )
			{
				$this->view->success = false;
			}
		}
	}
	
	
	
}